package com.qf.realm;

import com.qf.pojo.SysUsers;
import com.qf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author Wy
 * @version V1.0
 * @Project MavenDemo
 * @Package com.qf.realm
 * @Description:
 * @Date 2022/6/14 19:52
 */
public class MyUserRealm extends AuthorizingRealm {

     @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("=========自定义Realm,==doGetAuthorizationInfo方法, 授权: 根据用户名获取用户的角色权限数据赋予这个用户==============");
        //1. 获取认证的时候shiro框架中session存储的用户对象
        SysUsers users = (SysUsers) principalCollection.getPrimaryPrincipal();
        //获取id
        int id=users.getId();
        //调用方法
        Set rolesByUid = userService.findRolesByUid(id);
        //调用方法
        Set permByuid = userService.findPermByuid(id);
        //4. 封装shiro规定的角色权限对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(rolesByUid);
        simpleAuthorizationInfo.setStringPermissions(permByuid);


       //返回对象给核心
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("================自定义Realm, doGetAuthenticationInfo方法, 登录认证, 判断用户名密码是否正确==========================");
        //获取前端的输入的用户
        String principal = (String) token.getPrincipal();
        //获取前端页面输入的密码
        String credentials = new String((char[])token.getCredentials());
        //调用方法获取对象
        SysUsers userByName = userService.findUserByName(principal);
        if(userByName==null){
            throw new UnknownAccountException("用户不存在");
        }
        if(!credentials.equals(userByName.getPassword())){
            throw  new IncorrectCredentialsException("密码输入错误");
        }
        //7. 如果密码正确, 封装返回的用户对象给shiro框架的Securitymanager核心
        //第一参数:用户对象, 第二参数:密码, 第三参数: 当前自定义realm对象的名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userByName, credentials, this.getName());

        return info;
    }
}
